﻿using Castle.DynamicProxy;
using System;
using System.IO;
using System.Reflection;
using Yunzuan.Foundation.BusinessLogic.Interceptors;
using Yunzuan.Foundation.Exceptions;

namespace Yunzuan.Foundation.BusinessLogic
{
    public class ServiceFactory
    {
        public static T Create<T>() where T : class, new()
        {
            //MachineCode.Check();

            ProxyGenerator proxy = new ProxyGenerator();
            T target = proxy.CreateClassProxy<T>(ServiceInterceptor.Instance);
            return target;
        }

        public static object Create(Type type)
        {
            //MachineCode.Check();

            ProxyGenerator proxy = new ProxyGenerator();
            object target = proxy.CreateClassProxy(type, ServiceInterceptor.Instance);
            return target;
        }

        public static object Create(string typeName)
        {
            try
            {
                Type targetType = Type.GetType(typeName);
                return Create(targetType);
            }
            catch (FileNotFoundException)
            {
                throw new WarnException("没有找到程序集" + typeName);
            }
        }

        public static object Create(string assemblyName, string typeName)
        {
            try
            {
                Assembly assemblyBll = Assembly.LoadFrom(assemblyName);
                Type targetType = assemblyBll.GetType(typeName);
                return Create(targetType);
            }
            catch(FileNotFoundException)
            {
                throw new WarnException("没有找到程序集" + assemblyName + "->" + typeName);
            }
        }
    }
}
